var express = require('express');
var router = express.Router();
const cinemasService = require("../service/cinemasService")

/* GET users listing. */
//find
router.get('/', async function (require, resolve) {
    let { opt, text, current, size, flag } = require.query;
    let searchObj = {};
    if (opt && text) {
        if (!!flag || opt == 'tel') {
            searchObj[opt] = text;
        } else if (!flag) {
            searchObj[opt] = { $regex: text };
        }
    }
    let data = await cinemasService.find(searchObj, { current: current || 1, size: size || 5 });
    resolve.send(data);
});
// findById()
router.get('/:id', async function (require, resolve) {
    let id = require.params.id;
    let data = await cinemasService.findById(id);
    resolve.send(data);
})

// insert()
router.post('/', async function (require, resolve) {
    // console.log("post", require.body);
    if (require.body.screens) {
        require.body.screens = JSON.parse(require.body.screens);
        for(let item of require.body.screens){
            item.seat = JSON.parse(item.seat)
            console.log(item.seat);  
        }
    }
    console.log(require.body);
    let data = await cinemasService.insert(require.body);
    resolve.send(data);
})

// update()
router.put('/:id', async function (require, resolve) {
    let id = require.params.id;
    // console.log(require.body.screens);
    require.body.screens = JSON.parse(require.body.screens);
    let data = await cinemasService.update(id, require.body);
    resolve.send(data);
})

// delete()
router.delete('/:id', async function (require, resolve) {
    let id = require.params.id;
    let data = await cinemasService.delete(id);
    resolve.send(data);
})

module.exports = router;